/**
 * created by 小卷毛, 2021/04/30
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
@file:Suppress("unused")

package com.rzico.sbl.other

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.rzico.sbl.R
import com.xinnuo.loopview.LoopView
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.TimeHelper
import com.xinnuo.common.helper.getScreenWidth
import com.xinnuo.common.helper.shortToast
import com.xinnuo.common_ui.base.BottomDialog
import java.util.*

/**
 * 添加回访记录（R.layout.dialog_select_more 布局文件）
 * 返回格式 yyyy-MM-dd HH:mm
 *
 * LoopView 版本v0.2.2
 *
 * @param minYearValue    最小年份
 * @param initHour        默认时
 * @param initMinute      默认分
 * @param callback        回调接口
 */
fun Context.showTimeVisitDialog(
    minYearValue: Int = 2021,
    onShow: () -> Unit = {},
    onDismiss: () -> Unit = {},
    callback: (String, String) -> Unit = { _, _ -> }
) {

    @SuppressLint("StaticFieldLeak")
    val dialog = object : BottomDialog(this) {

        private lateinit var loopYear: LoopView
        private lateinit var loopMonth: LoopView
        private lateinit var loopDay: LoopView
        private lateinit var loopHour: LoopView
        private lateinit var loopMinute: LoopView
        private lateinit var loopTitle: TextView

        private val calendar = Calendar.getInstance()
        private val yearNow = calendar.get(Calendar.YEAR)
        private val monthNow = calendar.get(Calendar.MONTH) + 1
        private val dayNow = calendar.get(Calendar.DAY_OF_MONTH)
        private val hourNow = calendar.get(Calendar.HOUR_OF_DAY)
        private val minuteNow = calendar.get(Calendar.MINUTE)
        private val secondNow = calendar.get(Calendar.SECOND)

        private val listBig = listOf(1, 3, 5, 7, 8, 10, 12)
        private val listLittle = listOf(4, 6, 9, 11)

        private val listYear = ArrayList<Int>()
        private val listMonth = ArrayList<Int>()
        private val listDay = ArrayList<Int>()

        override fun onCreateView(): View {
            val view = inflate<View>(R.layout.dialog_time_visit)

            val tvCancel = view.findViewById<TextView>(R.id.dialog_cancle)
            val tvOk = view.findViewById<TextView>(R.id.dialog_ok)
            val etInput = view.findViewById<EditText>(R.id.dialog_memo)

            loopTitle = view.find(R.id.dialog_title)
            loopYear = view.find(R.id.dialog_year)
            loopMonth = view.find(R.id.dialog_month)
            loopDay = view.find(R.id.dialog_day)
            loopHour = view.find(R.id.dialog_hour)
            loopMinute = view.find(R.id.dialog_minute)

            loopYear.setTextSize(15f)
            loopMonth.setTextSize(15f)
            loopDay.setTextSize(15f)
            loopHour.setTextSize(15f)
            loopMinute.setTextSize(15f)

            loopYear.setDividerColor(getColorEx(R.color.divider))
            loopMonth.setDividerColor(getColorEx(R.color.divider))
            loopDay.setDividerColor(getColorEx(R.color.divider))
            loopHour.setDividerColor(getColorEx(R.color.divider))
            loopMinute.setDividerColor(getColorEx(R.color.divider))

            loopYear.setNotLoop()
            loopMonth.setNotLoop()
            loopDay.setNotLoop()
            loopHour.setNotLoop()
            loopMinute.setNotLoop()

            tvCancel.oneClick { dismiss() }

            tvOk.oneClick {
                val input = etInput.textTrim

                if (input.isEmpty()) {
                    this@showTimeVisitDialog.shortToast("请输入回访备注")
                    return@oneClick
                }

                val year = listYear[loopYear.selectedItem]
                val month = listMonth[loopMonth.selectedItem]
                val day = listDay[loopDay.selectedItem]
                val hour = loopHour.selectedItem
                val minute = loopMinute.selectedItem

                var dateNew: String = when {
                    month < 10 && day < 10 -> "$year-0$month-0$day"
                    month < 10 && day >= 10 -> "$year-0$month-$day"
                    month >= 10 && day < 10 -> "$year-$month-0$day"
                    else -> "$year-$month-$day"
                }

                dateNew += when {
                    hour < 10 && minute < 10 -> " 0$hour:0$minute"
                    hour < 10 && minute >= 10 -> " 0$hour:$minute"
                    hour >= 10 && minute < 10 -> " $hour:0$minute"
                    else -> " $hour:$minute"
                }

                dismiss()
                callback.invoke(dateNew, input)
            }

            return view
        }

        override fun setUiBeforShow() {
            var dateHint = when {
                monthNow < 10 && dayNow < 10 -> "$yearNow-0$monthNow-0$dayNow"
                monthNow < 10 && dayNow > 9 -> "$yearNow-0$monthNow-$dayNow"
                monthNow > 9 && dayNow < 10 -> "$yearNow-$monthNow-0$dayNow"
                else -> "$yearNow-$monthNow-$dayNow"
            }
            dateHint += when {
                hourNow < 10 && minuteNow < 10 -> " 0$hourNow:0$minuteNow:$secondNow"
                hourNow < 10 && minuteNow >= 10 -> " 0$hourNow:$minuteNow:$secondNow"
                hourNow >= 10 && minuteNow < 10 -> " $hourNow:0$minuteNow:$secondNow"
                else -> " $hourNow:$minuteNow:$secondNow"
            }
            loopTitle.text = dateHint

            loopYear.setItems(dateToList(minYearValue, yearNow, "%d年", listYear))
            loopYear.setInitPosition(yearNow - minYearValue)

            loopMonth.setItems(dateToList(1, monthNow, "%d月", listMonth))
            loopMonth.setInitPosition(monthNow - 1)

            loopDay.setItems(dateToList(1, dayNow, "%d日", listDay))
            loopDay.setInitPosition(dayNow - 1)

            loopHour.setItems(dateToList(0, 23, "%d时"))
            loopHour.setInitPosition(hourNow)

            loopMinute.setItems(dateToList(0, 59, "%d分"))
            loopMinute.setInitPosition(minuteNow)

            loopYear.setOnItemSelectedListener {
                val yearNum = listYear[loopYear.selectedItem]
                initMonth(yearNum)

                loopMonth.post { setTitleText() }
                loopDay.post { setTitleText() }
            }

            loopMonth.setOnItemSelectedListener {
                val yearNum = listYear[loopYear.selectedItem]
                val monthNum = listMonth[loopMonth.selectedItem]
                initDay(yearNum, monthNum)

                loopDay.post { setTitleText() }
            }

            loopDay.setOnItemSelectedListener { setTitleText() }
            loopHour.setOnItemSelectedListener { setTitleText() }
            loopMinute.setOnItemSelectedListener { setTitleText() }
        }

        /*
         * 根据年、限制条件来判断"月"的数据
         */
        private fun initMonth(year: Int) {
            val currentMonth = listMonth[loopMonth.selectedItem]
            if (year == yearNow) {
                loopMonth.setItems(dateToList(1, monthNow, "%d月", listMonth))
                if (currentMonth > monthNow) {
                    loopMonth.setCurrentPosition(monthNow - 1)
                    initDay(year, monthNow)
                } else {
                    initDay(year, currentMonth)
                }
            } else {
                loopMonth.setItems(dateToList(1, 12, "%d月", listMonth))
                initDay(year, currentMonth)
            }
        }

        /*
         * 根据年(是否闰年)、月(大小月)、限制条件来判断"日"的数据
         */
        private fun initDay(year: Int, month: Int) {
            val currentDay = listDay[loopDay.selectedItem]
            when (month) {
                in listBig -> {
                    if (year == yearNow && month == monthNow) {
                        loopDay.setItems(dateToList(1, dayNow, "%d日", listDay))
                        if (currentDay > dayNow) loopDay.setCurrentPosition(dayNow - 1)
                    } else {
                        loopDay.setItems(dateToList(1, 31, "%d日", listDay))
                    }
                }
                in listLittle -> {
                    if (year == yearNow && month == monthNow) {
                        loopDay.setItems(dateToList(1, dayNow, "%d日", listDay))
                        if (currentDay > dayNow) loopDay.setCurrentPosition(dayNow - 1)
                    } else {
                        loopDay.setItems(dateToList(1, 30, "%d日", listDay))
                        if (currentDay == 31) loopDay.setCurrentPosition(29)
                    }
                }
                else -> {
                    if (TimeHelper.getInstance().isLeapYear(year)) {
                        if (year == yearNow && month == monthNow) {
                            loopDay.setItems(dateToList(1, dayNow, "%d日", listDay))
                            if (currentDay > dayNow) loopDay.setCurrentPosition(dayNow - 1)
                        } else {
                            loopDay.setItems(dateToList(1, 29, "%d日", listDay))
                            if (currentDay > 29) loopDay.setCurrentPosition(28)
                        }
                    } else {
                        if (year == yearNow && month == monthNow) {
                            loopDay.setItems(dateToList(1, dayNow, "%d日", listDay))
                            if (currentDay > dayNow) loopDay.setCurrentPosition(dayNow - 1)
                        } else {
                            loopDay.setItems(dateToList(1, 28, "%d日", listDay))
                            if (currentDay > 28) loopDay.setCurrentPosition(27)
                        }
                    }
                }
            }
        }

        private fun setTitleText() {
            val yearNum = listYear[loopYear.selectedItem]
            val monthNum = listMonth[loopMonth.selectedItem]
            val dayNum = listDay[loopDay.selectedItem]
            val dayHour = loopHour.selectedItem
            val dayMinute = loopMinute.selectedItem

            var dateHint = when {
                monthNum < 10 && dayNum < 10 -> "$yearNum-0$monthNum-0$dayNum"
                monthNum < 10 && dayNum > 9 -> "$yearNum-0$monthNum-$dayNum"
                monthNum > 9 && dayNum < 10 -> "$yearNum-$monthNum-0$dayNum"
                else -> "$yearNum-$monthNum-$dayNum"
            }

            dateHint += when {
                dayHour < 10 && dayMinute < 10 -> " 0$dayHour:0$dayMinute:00"
                dayHour < 10 && dayMinute >= 10 -> " 0$dayHour:$dayMinute:00"
                dayHour >= 10 && dayMinute < 10 -> " $dayHour:0$dayMinute:00"
                else -> " $dayHour:$dayMinute:00"
            }

            loopTitle.text = dateHint
        }
    }

    dialog.setOnShowListener { onShow() }
    dialog.setOnDismissListener { onDismiss() }
    dialog.show()

    dialog
        .window
        ?.attributes = dialog.window?.attributes.apply {
        this?.width = getScreenWidth() //设置宽度
    }
}

private fun dateToList(
    minValue: Int,
    maxValue: Int,
    format: String = "",
    list: ArrayList<Int>? = null
): List<String> {
    val items = ArrayList<String>()
    list?.clear()

    for (value in minValue..maxValue) {
        list?.add(value)
        items.add(
            if (format.isEmpty()) value.toString()
            else String.format(format, value)
        )
    }
    return items
}

/**
 * 客户转移弹框
 */
fun Context.showTransferDialog(
    items: List<String>,
    listener: (Int, String, String) -> Unit = { _, _, _ -> }
) {

    lateinit var loopView: LoopView

    val dialog = object : BottomDialog(this) {

        override fun onCreateView(): View {
            val view = inflate<View>(R.layout.dialog_master_transfer)

            val tvCancel = view.findViewById<TextView>(R.id.dialog_cancle)
            val tvOk = view.findViewById<TextView>(R.id.dialog_ok)
            val etInput = view.findViewById<EditText>(R.id.dialog_memo)
            loopView = view.find(R.id.dialog_list)

            loopView.setTextSize(15f)
            loopView.setDividerColor(getColorEx(R.color.divider))
            loopView.setNotLoop()

            tvCancel.oneClick { dismiss() }

            tvOk.oneClick {
                dismiss()
                listener.invoke(
                    loopView.selectedItem,
                    items[loopView.selectedItem],
                    etInput.textTrim
                )
            }

            return view
        }

        override fun setUiBeforShow() {
            loopView.setItems(items)
        }

    }

    dialog.show()

    dialog.window
        ?.attributes = dialog.window?.attributes.apply {
        this?.width = getScreenWidth() //设置宽度
    }
}
